package com.xatl.simulated.client;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.*;


@Slf4j
public class MqttReceiveCallback implements MqttCallbackExtended {

    private MqttClient mqttClient;
    private String topic;
    private int qos;

    MqttReceiveCallback(MqttClient mqttClient, String topic, int qos) {
        this.mqttClient = mqttClient;
        this.topic = topic;
        this.qos = qos;

    }

    @Override
    public void connectionLost(Throwable cause) {
        log.warn("mqtt client connection lost! Cause by {}", cause.getCause());
        int i = 3;
        while(true){
            if (i < 0) {
                //这里是我自己为了失败3次后告警使用
                log.error("mqtt链接丢失");
                break;
            }

            if(mqttClient != null && !mqttClient.isConnected()){
                log.warn("***** client to connect *****");
                try {
                    //这个是3秒后重连
                    Thread.sleep(3000);
                    mqttClient.reconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                i--;
            }

            if (mqttClient != null && mqttClient.isConnected()) {
                log.info("*****mqtt connect success *****");
                break;
            }
        }

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("============Mqtt Message============");
        log.info("接收消息内容："+new String(message.getPayload()));



    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("消息是否成功发送至MQTT服务器=============" + token.isComplete());
    }

    @Override
    public void connectComplete(boolean b, String s) {
        try {
            log.info("重新初始化订阅!");
            mqttClient.subscribe(topic, qos);
        } catch (MqttException e) {
            log.error("Failed to subscribe again! Cause by {}", e.getCause());
        }
    }

}